import storage from 'good-storage';
const SEARCH_KEY = '__search__';
const SEARCH_MAX_LENGTH=15;

const PLAY_KEY = '__play__';
const PLAY_MAX_LENGTH=200;

const FAVORITE_KEY = '__favorite__';
const FAVORITE_MAX_LENGTH=200;
// 插入数组,判断index 是否存在,存在 删除,插入一个值在0这个值
function insertArray(arr,val,compare,maxLen){
	const index=arr.findIndex(compare);
	if(index===0){
		return
	}
	if(index>0){
		arr.splice(index,1)
	}
	arr.unshift(val)
	if(maxLen&&arr.length>maxLen){
		arr.pop()
	}
}
//保存搜索记录
export function saveSearch(query){
	let searches=storage.get(SEARCH_KEY,[]); 
	insertArray(searches,query,(item)=>{
		return item===query
	},SEARCH_MAX_LENGTH);
	storage.set(SEARCH_KEY,searches)
	return searches
}
//删除指定index的数组
function delectFromArray(arr,compare){
	const index=arr.findIndex(compare);
		if (index>-1) {
			arr.splice(index,1)
		}
}
//删除 搜索
export function deleteSearch(query){
	let searches=storage.get(SEARCH_KEY,[]); 
	delectFromArray(searches,(item)=>{
		return item ===query
	})
	storage.set(SEARCH_KEY,searches)
	return searches
}
//删除 清空 缓存
export function clearSearch(){
	storage.remove(SEARCH_KEY);
	return []
}
// 重载 搜索记录
export function loadSearch() {
  return storage.get(SEARCH_KEY, [])
}
// 保存 play 
export function savePlay(song){
	let songs=storage.get(PLAY_KEY,[]); 
	insertArray(songs,song,(item)=>{
		return item.id===song.id
	},PLAY_MAX_LENGTH);
	storage.set(PLAY_KEY,songs)
	return songs
}
// 重载 play
export function loadPlay(song){
	return storage.get(PLAY_KEY,[]); 
}
// 保存 最爱
export function saveFavorite(song){
	let songs=storage.get(FAVORITE_KEY,[]); 
	insertArray(songs,song,(item)=>{
		return item.id===song.id
	},FAVORITE_MAX_LENGTH);
	storage.set(FAVORITE_KEY,songs)
	return songs
}
// 删除 最爱
export function deleteFavorite(song){
let songs=storage.get(FAVORITE_KEY,[]); 
	delectFromArray(songs,(item)=>{
		return item.id===song.id
	})
	storage.set(FAVORITE_KEY,songs)
	return songs
}

export function loadFavorite(){
	return storage.get(FAVORITE_KEY,[]);
}